package com.sq.util.web;

import java.io.IOException;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.AbstractHttpMessage;
import org.apache.http.util.EntityUtils;

import com.sq.util.exception.CommonException;

/**
 * @author sq
 *
 */
class BaseHttpUtil {
    static RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(6000).setConnectTimeout(6000)
            .setConnectionRequestTimeout(6000).build();

    private final static int HTTP_OK_START = 200;
    private final static int HTTP_OK_END = 299;

    static PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();

    static {
        cm.setMaxTotal(100);
        cm.setDefaultMaxPerRoute(100);
        cm.setValidateAfterInactivity(3000);
    }

    static void setHeaders(AbstractHttpMessage request, Map<String, String> headers) {
        if (headers == null) {
            return;
        }
        if (headers.size() == 0) {
            return;
        }
        for (Map.Entry<String, String> entry : headers.entrySet()) {
            request.setHeader(entry.getKey(), entry.getValue());
        }
    }

    static String request(HttpRequestBase request, String charset) throws Exception {
        request.setConfig(requestConfig);
        // NOTE 使用连接池，这个client是不用关闭的
        CloseableHttpClient httpClient = getHttpClient();
        try (CloseableHttpResponse response = httpClient.execute(request)) {
            checkResponseHttpCode(response, charset);
            HttpEntity entity = response.getEntity();
            if (entity == null || entity.getContent() == null) {
                return null;
            }
            return EntityUtils.toString(entity, charset);
        } catch (Exception e) {
            throw e;
        }
    }

    private static void checkResponseHttpCode(CloseableHttpResponse response, String charset) throws IOException {
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode >= HTTP_OK_START && statusCode <= HTTP_OK_END) {
            return;
        }
        String msg = "";
        HttpEntity entity = response.getEntity();
        if (entity != null && entity.getContent() != null) {
            msg = ",异常信息:" + EntityUtils.toString(entity, charset);
        }
        throw new CommonException("返回码:" + statusCode + msg);
    }

    private static CloseableHttpClient getHttpClient() {
        return HttpClients.custom().setConnectionManager(cm).build();
    }
}
